package cn.elane.elastic.global.util;

import cn.elane.elastic.global.model.NameBean;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;

public class HttpUtil {

	/***
	 * post
	 * @param address    链接地址
	 * @param param        参数：{\"key\":\"value\"}
	 * @return String    结果
	 */
	public static String post(String address, String param) {
		try {
//			System.out.println(URLDecoder.decode(address, "UTF-8"));
			URL url = new URL(URLDecoder.decode(address, "UTF-8"));
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
			connection.connect();
			//POST请求
			if (param != null) {
				DataOutputStream out = new DataOutputStream(connection.getOutputStream());
				String soapRequestJson = param;
				out.write(soapRequestJson.getBytes(StandardCharsets.UTF_8));
				out.flush();
			}
			//读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes());
				sb.append(lines);
			}
			reader.close();
			connection.disconnect();
			return sb.toString();
		} catch (Exception e) {
//            e.printStackTrace();
			return "";
		}
	}

	/**
	 * post
	 * @param address    链接地址
	 * @param header        参数：{\"key\":\"value\"}
	 * @param body        参数：{\"key\":\"value\"}
	 * @return String    结果
	 */
	public static String post2(String address, NameBean header, NameBean body) {
		try {
//			System.out.println(URLDecoder.decode(address, "UTF-8"));
			URL url = new URL(URLDecoder.decode(address, "UTF-8"));
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

			if (header != null && !header.isEmpty()) {
				Set<String> key = header.keySet();
				for (String s : key) {
					connection.setRequestProperty(s, header.str(s));
				}
			}

			connection.connect();
			//POST请求
			if (body != null) {
				DataOutputStream out = new DataOutputStream(connection.getOutputStream());
				String soapRequestJson = body.toJson();
				out.write(soapRequestJson.getBytes(StandardCharsets.UTF_8));
				out.flush();
			}
			//读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes());
				sb.append(lines);
			}
			reader.close();
			connection.disconnect();
			return sb.toString();
		} catch (Exception e) {
//            e.printStackTrace();
			return "";
		}
	}

	/**
	 * post
	 * @param address    链接地址
	 * @param header        参数：{\"key\":\"value\"}
	 * @param body        参数：{\"key\":\"value\"}
	 * @return String    结果
	 */
	public static String post2(String address, NameBean header, JSONObject body) {
		HttpURLConnection connection = null;
		OutputStream os= null;
		DataOutputStream out = null;
		InputStream is = null;
		InputStreamReader isr =null;
		BufferedReader reader=null;
		try {
			URL url = new URL(URLDecoder.decode(address, "UTF-8"));
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

			if (header != null && !header.isEmpty()) {
				Set<String> key = header.keySet();
				for (String s : key) {
					connection.setRequestProperty(s, header.str(s));
				}
			}

			connection.connect();
			//POST请求
			if (body != null) {
				os=connection.getOutputStream();
				out = new DataOutputStream(os);
				String soapRequestJson = body.toJSONString();
				out.write(soapRequestJson.getBytes(StandardCharsets.UTF_8));
				out.flush();
			}

			//读取响应
			is=connection.getInputStream();
			isr=new InputStreamReader(is,StandardCharsets.UTF_8);
			reader = new BufferedReader(isr);
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes());
				sb.append(lines);
			}
			return sb.toString();
		} catch (Exception e) {
            e.printStackTrace();
			return "";
		}finally {
			if(null != reader){
				try{
					reader.close();
				}catch (Exception e){}
			}
			if(null != isr){
				try{
					isr.close();
				}catch (Exception e){}
			}
			if(null != is){
				try{
					is.close();
				}catch (Exception e){}
			}
			if(null != out){
				try{
					out.close();
				}catch (Exception e){}
			}
			if(null != os){
				try{
					os.close();
				}catch (Exception e){}
			}
			if(null != connection){
				try{
					connection.disconnect();
				}catch (Exception e){}
			}
		}
	}

	public static String post3(String address, NameBean header, JSONObject body) {
		try{
			Thread.sleep(100);
		}catch (Exception e){}
		HttpURLConnection connection = null;
		OutputStream os= null;
		DataOutputStream out = null;
		InputStream is = null;
		InputStreamReader isr =null;
		BufferedReader reader=null;
		try {
			URL url = new URL(URLDecoder.decode(address, "UTF-8"));
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

			if (header != null && !header.isEmpty()) {
				Set<String> key = header.keySet();
				for (String s : key) {
					connection.setRequestProperty(s, header.str(s));
				}
			}

			connection.connect();
			//POST请求
			if (body != null) {
				os=connection.getOutputStream();
				out = new DataOutputStream(os);
				String soapRequestJson = body.toJSONString();
				out.write(soapRequestJson.getBytes(StandardCharsets.UTF_8));
				out.flush();
			}

			//读取响应
			is=connection.getInputStream();
			isr=new InputStreamReader(is,StandardCharsets.UTF_8);
			reader = new BufferedReader(isr);
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes());
				sb.append(lines);
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}finally {
			if(null != reader){
				try{
					reader.close();
				}catch (Exception e){}
			}
			if(null != isr){
				try{
					isr.close();
				}catch (Exception e){}
			}
			if(null != is){
				try{
					is.close();
				}catch (Exception e){}
			}
			if(null != out){
				try{
					out.close();
				}catch (Exception e){}
			}
			if(null != os){
				try{
					os.close();
				}catch (Exception e){}
			}
			if(null != connection){
				try{
					connection.disconnect();
				}catch (Exception e){}
			}
		}
	}

	/***
	 * get
	 * @param address    链接地址
	 * @param
	 * @return String    结果
	 */
	public static String get(String address) {
//		System.err.println(address);
		try {
			URL url = new URL(address);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true); // 设置该连接是可以输出的
			connection.setRequestMethod("GET"); // 设置请求方式
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			connection.connect();
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
			StringBuilder result = new StringBuilder();
			String line = null;
			while ((line = br.readLine()) != null) { // 读取数据
				line = new String(line.getBytes());
				result.append(line);
			}
			connection.disconnect();
			return result.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	//TODO: 根据param组件 key=val&key1=val1

	/**
	 * get
	 *
	 * @param address 链接地址
	 * @param
	 * @return String    结果
	 */
	public static String get(String address, NameBean param) {
		try {
			URL url = new URL(address);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true); // 设置该连接是可以输出的
			connection.setRequestMethod("GET"); // 设置请求方式
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			connection.connect();
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			StringBuilder result = new StringBuilder();
			String line = null;
			while ((line = br.readLine()) != null) { // 读取数据
				line = new String(line.getBytes());
				result.append(line);
			}
			connection.disconnect();
			return result.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static void main(String[] args) {
		/*String url = "http://172.1.103.111:5601/api/kibana/suggestions/values/apm-*";
		NameBean header = new NameBean();
		NameBean body = new NameBean();
		header.put("kbn-version", "7.11.1");
		body.init("{" +
				"    \"query\": \"\"," +
				"    \"field\": \"service.name\"," +
				"    \"filters\": []" +
				"}");

		String s = post2(url, header, body);
		System.err.println(s);*/

	}
}
